"""
实验模板管理 API 路由
"""
import json
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional

from database import get_db
from schemas.template_schema import (
    ExperimentTemplateCreate,
    ExperimentTemplateUpdate,
    ExperimentTemplateResponse,
    ExperimentTemplateListResponse,
    ExperimentTemplateDetailResponse,
    VersionDiffResponse
)
from services.template_service import TemplateService

router = APIRouter(prefix="/api/experiment-templates", tags=["实验模板管理"])


@router.post("", response_model=ExperimentTemplateResponse, summary="创建实验模板")
def create_template(
    template_create: ExperimentTemplateCreate,
    db: Session = Depends(get_db)
):
    """
    创建实验模板

    - **name**: 模板名称(必填)
    - **description**: 模板描述(可选)
    - **yaml_content**: YAML 内容字符串(必填)
    - **tags**: 标签列表(可选)
    """
    success, error_msg, template = TemplateService.create_template(db, template_create)

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    # 解析 tags
    tags = json.loads(template.tags) if template.tags else []

    return ExperimentTemplateResponse(
        id=template.id,
        name=template.name,
        description=template.description,
        application_id=template.application_id,
        tags=tags,
        version=template.version,
        created_at=template.created_at,
        updated_at=template.updated_at
    )


@router.get("", response_model=ExperimentTemplateListResponse, summary="查询模板列表")
def get_template_list(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="模板名称(模糊查询)"),
    tags: Optional[str] = Query(None, description="标签(逗号分隔)"),
    sort_by: str = Query("created_at", description="排序字段(name/created_at/updated_at)"),
    order: str = Query("desc", description="排序方向(asc/desc)"),
    db: Session = Depends(get_db)
):
    """
    查询模板列表

    支持分页、筛选、排序
    """
    total, templates = TemplateService.get_template_list(
        db, page, page_size, name, tags, sort_by, order
    )

    items = []
    for template in templates:
        tags_list = json.loads(template.tags) if template.tags else []
        items.append(ExperimentTemplateResponse(
            id=template.id,
            name=template.name,
            description=template.description,
            application_id=template.application_id,
            tags=tags_list,
            version=template.version,
            created_at=template.created_at,
            updated_at=template.updated_at
        ))

    return ExperimentTemplateListResponse(
        total=total,
        page=page,
        page_size=page_size,
        items=items
    )


@router.get("/{template_id}", response_model=ExperimentTemplateDetailResponse, summary="查询模板详情")
def get_template_detail(
    template_id: int,
    db: Session = Depends(get_db)
):
    """
    查询模板详情

    包括完整的 YAML 配置和版本历史
    """
    template = TemplateService.get_template_by_id(db, template_id)

    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")

    # 获取版本历史
    version_history = TemplateService.get_version_history(db, template_id)

    # 解析数据
    tags = json.loads(template.tags) if template.tags else []
    json_config = json.loads(template.json_config)

    return ExperimentTemplateDetailResponse(
        id=template.id,
        name=template.name,
        description=template.description,
        yaml_content=template.yaml_content,
        json_config=json_config,
        application_id=template.application_id,
        tags=tags,
        version=template.version,
        version_history=version_history,
        created_at=template.created_at,
        updated_at=template.updated_at,
        created_by=template.created_by
    )


@router.put("/{template_id}", response_model=ExperimentTemplateResponse, summary="更新模板")
def update_template(
    template_id: int,
    template_update: ExperimentTemplateUpdate,
    db: Session = Depends(get_db)
):
    """
    更新模板

    每次更新会自动生成新版本
    """
    success, error_msg, new_template = TemplateService.update_template(
        db, template_id, template_update
    )

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    tags = json.loads(new_template.tags) if new_template.tags else []

    return ExperimentTemplateResponse(
        id=new_template.id,
        name=new_template.name,
        description=new_template.description,
        application_id=new_template.application_id,
        tags=tags,
        version=new_template.version,
        created_at=new_template.created_at,
        updated_at=new_template.updated_at
    )


@router.delete("/{template_id}", summary="删除模板")
def delete_template(
    template_id: int,
    db: Session = Depends(get_db)
):
    """
    删除模板(软删除)
    """
    success, error_msg = TemplateService.delete_template(db, template_id)

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    return {"message": "模板已删除"}


@router.get("/{template_id}/versions/diff", response_model=VersionDiffResponse, summary="版本对比")
def get_version_diff(
    template_id: int,
    version1: int = Query(..., description="版本号1"),
    version2: int = Query(..., description="版本号2"),
    db: Session = Depends(get_db)
):
    """
    对比两个版本的差异
    """
    success, error_msg, diff_data = TemplateService.get_version_diff(
        db, template_id, version1, version2
    )

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    return VersionDiffResponse(
        version1=diff_data["version1"],
        version2=diff_data["version2"],
        diff=diff_data["diff"]
    )


@router.post("/{template_id}/versions/{version}/rollback", response_model=ExperimentTemplateResponse, summary="版本回滚")
def rollback_to_version(
    template_id: int,
    version: int,
    db: Session = Depends(get_db)
):
    """
    回滚到指定版本

    回滚后会生成新版本,而非覆盖当前版本
    """
    success, error_msg, new_template = TemplateService.rollback_to_version(
        db, template_id, version
    )

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    tags = json.loads(new_template.tags) if new_template.tags else []

    return ExperimentTemplateResponse(
        id=new_template.id,
        name=new_template.name,
        description=new_template.description,
        application_id=new_template.application_id,
        tags=tags,
        version=new_template.version,
        created_at=new_template.created_at,
        updated_at=new_template.updated_at
    )
